<template>
  <el-dialog v-model="visible" :title="mode === 'edit' ? '编辑项目' : '创建新项目'" width="800px" :close-on-click-modal="false">
    <div class="dialog-flex">
      <!-- 左侧表单 -->
      <div class="dialog-left">
        <el-form
          ref="formRef"
          :model="{ projectName, projectFolder }"
          :rules="rules"
        >
          <el-form-item>
            <el-input
              v-model="projectName"
              placeholder="项目名称"
              :maxlength="30"
              clearable
            />
          </el-form-item>
          <el-form-item>
            <el-input
              v-model="projectDesc"
              type="textarea"
              :rows="3"
              placeholder="项目描述（可选）"
            />
          </el-form-item>
          <el-form-item prop="projectFolder">
            <el-tree-select
              v-model="projectFolder"
              :data="folderTree"
              :props="{ label: 'name', value: 'id', children: 'children' }"
              placeholder="项目文件夹（必选）"
              check-strictly
              style="width: 100%;"
              node-key="id"
              :default-expand-all="true"
              clearable
              required
            />
          </el-form-item>
          <el-form-item>
            <div class="cover-upload">
              <el-upload
                ref="uploadRef"
                class="upload-demo"
                action=""
                :show-file-list="false"
                :auto-upload="false"
                :on-change="handleCoverChange"
                accept="image/*"
              >
                <template #trigger>
                  <div class="cover-upload-inner">
                    <el-icon style="font-size:40px;color:#bcbcff;"><Picture /></el-icon>
                    <div style="color:#888;margin-top:8px;">点击添加项目封面图片（可选）</div>
                  </div>
                </template>
              </el-upload>
              <img v-if="coverImage" :src="coverImage" class="cover-preview" />
            </div>
          </el-form-item>
        </el-form>
      </div>
      <!-- 右侧模板选择 -->
      <div class="dialog-right">
        <div class="template-title">选择模板</div>
        <div class="template-list">
          <div
            v-for="tpl in templates"
            :key="tpl.id"
            :class="['template-item', { active: selectedTemplate === tpl.id }]"
            @click="selectTemplate(tpl.id)"
          >
            <div class="template-name">{{ tpl.name }}</div>
            <div class="template-desc">{{ tpl.desc }}</div>
          </div>
        </div>
      </div>
    </div>
    <template #footer>
      <el-button @click="onCancel">取消</el-button>
      <el-button type="primary" :disabled="!projectName" @click="onSave">{{ mode === 'edit' ? '保存' : '创建' }}</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, defineProps, defineEmits, watch, onMounted } from 'vue'
import { Folder, Picture } from '@element-plus/icons-vue'
import { getTemplateList } from '@/api/templateApi'
import { getDirectoryList } from '@/api/directoryApi.js'
import { upload } from '@/api/commonApi'
import { ElMessage } from 'element-plus'

const props = defineProps({
  modelValue: Boolean,
  folderOptions: {
    type: Array,
    default: () => []
  },
  defaultFolder: {
    type: [String, Number, null],
    default: null
  },
  projectData: {
    type: Object,
    default: null
  },
  mode: {
    type: String,
    default: 'create' // 'create' or 'edit'
  }
})
const emit = defineEmits(['update:modelValue', 'create', 'edit'])

const visible = ref(props.modelValue)
const projectName = ref('')
const projectDesc = ref('')
const projectFolder = ref('')
const coverImage = ref('')
const uploadRef = ref(null)

const templates = ref([])
const selectedTemplate = ref(null)
const folderTree = ref([])
const formRef = ref(null)
const rules = {
  projectName: [
    { required: true, message: '请输入项目名称', trigger: 'blur' }
  ],
  projectFolder: [
    { required: true, message: '请选择项目文件夹', trigger: 'change' }
  ]
}

const DEFAULT_COVER = 'https://sky-story.oss-cn-beijing.aliyuncs.com/a2c0abae-a7bf-43dd-8948-b0f4910211ec.webp'

onMounted(async () => {
  try {
    const res = await getTemplateList()
    if (Array.isArray(res)) {
      templates.value = res.map(tpl => ({
        id: tpl.id,
        name: tpl.name,
        desc: tpl.description
      }))
      if (templates.value.length > 0) selectedTemplate.value = templates.value[0].id
    }
    // 获取文件夹树
    const dirRes = await getDirectoryList({ userId: 1 })
    if (Array.isArray(dirRes)) {
      folderTree.value = dirRes
    }
  } catch (e) {
    templates.value = []
    folderTree.value = []
  }
})

watch(() => props.modelValue, v => visible.value = v)
watch(visible, v => emit('update:modelValue', v))

watch(
  () => props.defaultFolder,
  (val) => {
    if (val !== undefined && val !== null) {
      projectFolder.value = val;
    }
  },
  { immediate: true }
)

watch(
  () => props.projectData,
  (val) => {
    if (val && props.mode === 'edit') {
      projectName.value = val.name || ''
      projectDesc.value = val.description || ''
      projectFolder.value = val.directoryId || ''
      coverImage.value = val.coverImage || DEFAULT_COVER
      selectedTemplate.value = val.templateId || (templates.value.length > 0 ? templates.value[0].id : null)
    } else if (props.mode === 'create') {
      resetForm()
    }
  },
  { immediate: true }
)

watch(
  folderTree,
  (val) => {
    if (val && val.length > 0 && !projectFolder.value) {
      // 递归找到第一个有 id 的节点
      function findFirstIdNode(nodes) {
        for (const node of nodes) {
          if (node.id) return node.id;
          if (node.children && node.children.length > 0) {
            const childId = findFirstIdNode(node.children);
            if (childId) return childId;
          }
        }
        return null;
      }
      const firstId = findFirstIdNode(val);
      if (firstId) projectFolder.value = firstId;
    }
  },
  { immediate: true }
)

function resetForm() {
  projectName.value = ''
  projectDesc.value = ''
  projectFolder.value = ''
  coverImage.value = DEFAULT_COVER
  selectedTemplate.value = templates.value.length > 0 ? templates.value[0].id : null
}

function onCancel() {
  visible.value = false
}

function onSave() {
  formRef.value.validate((valid) => {
    if (!valid) return;
    const payload = {
      name: projectName.value,
      description: projectDesc.value,
      directoryId: projectFolder.value,
      coverImage: coverImage.value,
      templateId: selectedTemplate.value
    }
    if (props.mode === 'edit') {
      emit('edit', { ...props.projectData, ...payload })
    } else {
      emit('create', payload)
    }
    visible.value = false
    resetForm()
  })
}

async function handleCoverChange(file) {
  try {
    const res = await upload(file.raw)
    coverImage.value = res.url;
  } catch (e) {
    ElMessage.error('图片上传失败')
  }
}
function selectTemplate(id) {
  selectedTemplate.value = id
}
</script>

<style scoped>
.dialog-flex {
  display: flex;
  gap: 32px;
}
.dialog-left {
  flex: 1.2;
}
.dialog-right {
  flex: 1;
  padding-left: 32px;
  min-width: 220px;
}
.template-title {
  font-weight: bold;
  margin-bottom: 16px;
  font-size: 16px;
}
.template-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}
.template-item {
  border: 1.5px solid #e5e7eb;
  border-radius: 10px;
  padding: 16px;
  cursor: pointer;
  transition: border 0.2s, box-shadow 0.2s;
}
.template-item.active {
  border: 1.5px solid #6366f1;
  box-shadow: 0 2px 8px #6366f122;
  background: #f5f6ff;
}
.template-name {
  font-weight: 600;
  margin-bottom: 6px;
}
.template-desc {
  color: #888;
  font-size: 13px;
}
.cover-upload {
  width: 100%;
  min-height: 120px;
  border: 1.5px dashed #e5e7eb;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  position: relative;
  background: #fafbff;
}
.cover-upload-inner {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  padding: 24px 0;
}
.cover-preview {
  display: block;
  width: 180px;
  height: 120px;
  object-fit: cover;
  border-radius: 16px;
  box-shadow: 0 4px 16px #bcbcff33;
  border: 2px solid #ececff;
  transition: transform 0.18s, box-shadow 0.18s;
}
.cover-preview:hover {
  transform: scale(1.05);
  box-shadow: 0 8px 24px #6366f144;
}
</style> 